Your First AI application¶
Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.
The project is broken down into multiple steps:
- Load the image dataset and create a pipeline.
- Build and Train an image classifier on this dataset.
- Use your trained model to perform inference on flower images.
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
Import Resources¶
# TODO: Make all necessary imports.
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_datasets as tfds
tfds.disable_progress_bar() # disabled to minimize clutter
from tensorflow.keras import layers, models, regularizers
from tensorflow.keras.callbacks import EarlyStopping, Callback
from tensorflow.keras.models import load_model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import InputLayer, Activation, Dropout, Dense, Conv2D, Flatten, Dropout, MaxPooling2D, BatchNormalization
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR) # to minimize clutter
import json
import tensorflow_hub as hub
from PIL import Image
# Printing to ensure the environment is correctly set up for development
print('Using:')
print('\t\u2022 TensorFlow version:', tf.__version__)
print('\t\u2022 Running on GPU' if tf.test.is_gpu_available() else '\t\u2022 GPU device not found. Running on CPU')
Using: • TensorFlow version: 2.14.0 • Running on GPU
Load the Dataset¶
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# TODO: Load the dataset with TensorFlow Datasets.
dataset, info_set = tfds.load('oxford_flowers102', as_supervised=True, with_info=True)
# TODO: Create a training set, a validation set and a test set.
training_set = dataset['train']
validation_set = dataset['validation']
test_set = dataset['test']
# Having a glimpse into the dataset info to familarize myself with it's background
info_set
tfds.core.DatasetInfo(
name='oxford_flowers102',
full_name='oxford_flowers102/2.1.1',
description="""
The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly
occurring in the United Kingdom. Each class consists of between 40 and 258
images. The images have large scale, pose and light variations. In addition,
there are categories that have large variations within the category and several
very similar categories.
The dataset is divided into a training set, a validation set and a test set. The
training set and validation set each consist of 10 images per class (totalling
1020 images each). The test set consists of the remaining 6149 images (minimum
20 per class).
Note: The dataset by default comes with a test size larger than the train size.
For more info see this
[issue](https://github.com/tensorflow/datasets/issues/3022).
""",
homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
data_dir=PosixGPath('/tmp/tmptp2cu9eqtfds'),
file_format=tfrecord,
download_size=328.90 MiB,
dataset_size=331.34 MiB,
features=FeaturesDict({
'file_name': Text(shape=(), dtype=string),
'image': Image(shape=(None, None, 3), dtype=uint8),
'label': ClassLabel(shape=(), dtype=int64, num_classes=102),
}),
supervised_keys=('image', 'label'),
disable_shuffling=False,
splits={
'test': <SplitInfo num_examples=6149, num_shards=2>,
'train': <SplitInfo num_examples=1020, num_shards=1>,
'validation': <SplitInfo num_examples=1020, num_shards=1>,
},
citation="""@InProceedings{Nilsback08,
author = "Nilsback, M-E. and Zisserman, A.",
title = "Automated Flower Classification over a Large Number of Classes",
booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
year = "2008",
month = "Dec"
}""",
)
Explore the Dataset¶
# TODO: Get the number of examples in each set from the dataset info.
print(f"Number of examples => "
f"Train: {info_set.splits['train'].num_examples}, "
f"Validation: {info_set.splits['validation'].num_examples}, "
f"Test: {info_set.splits['test'].num_examples}")
# TODO: Get the number of classes in the dataset from the dataset info.
print(f"Number of classes: {info_set.features['label'].num_classes}")
Number of examples => Train: 1020, Validation: 1020, Test: 6149 Number of classes: 102
# TODO: Print the shape and corresponding label of 3 images in the training set.
print("The first 3 images from the dataset before applying normalization yet:")
print("----------------------------------------------------------------------")
for i, (image, label) in enumerate(training_set.take(3)):
print(f"Image {i+1}:")
print(f" Shape: {image.shape}")
print(f" Label: {label}")
print()
The first 3 images from the dataset before applying normalization yet: ---------------------------------------------------------------------- Image 1: Shape: (500, 667, 3) Label: 72 Image 2: Shape: (500, 666, 3) Label: 84 Image 3: Shape: (670, 500, 3) Label: 70
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding image label.
for image, label in training_set.take(1):
first_image = image.numpy()
first_label = label.numpy()
plt.imshow(first_image)
plt.title(f"Label: {first_label}")
plt.axis('off')
plt.show()
Label Mapping¶
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
with open('label_map.json', 'r') as f:
class_names = json.load(f)
# I'm just Printing the Map out of curiosity
print("Class Names found in the label_map file:")
print(json.dumps(class_names, indent=4))
Class Names found in the label_map file:
{
"0": "pink primrose",
"1": "hard-leaved pocket orchid",
"2": "canterbury bells",
"3": "sweet pea",
"4": "english marigold",
"5": "tiger lily",
"6": "moon orchid",
"7": "bird of paradise",
"8": "monkshood",
"9": "globe thistle",
"10": "snapdragon",
"11": "colt's foot",
"12": "king protea",
"13": "spear thistle",
"14": "yellow iris",
"15": "globe-flower",
"16": "purple coneflower",
"17": "peruvian lily",
"18": "balloon flower",
"19": "giant white arum lily",
"20": "fire lily",
"21": "pincushion flower",
"22": "fritillary",
"23": "red ginger",
"24": "grape hyacinth",
"25": "corn poppy",
"26": "prince of wales feathers",
"27": "stemless gentian",
"28": "artichoke",
"29": "sweet william",
"30": "carnation",
"31": "garden phlox",
"32": "love in the mist",
"33": "mexican aster",
"34": "alpine sea holly",
"35": "ruby-lipped cattleya",
"36": "cape flower",
"37": "great masterwort",
"38": "siam tulip",
"39": "lenten rose",
"40": "barbeton daisy",
"41": "daffodil",
"42": "sword lily",
"43": "poinsettia",
"44": "bolero deep blue",
"45": "wallflower",
"46": "marigold",
"47": "buttercup",
"48": "oxeye daisy",
"49": "common dandelion",
"50": "petunia",
"51": "wild pansy",
"52": "primula",
"53": "sunflower",
"54": "pelargonium",
"55": "bishop of llandaff",
"56": "gaura",
"57": "geranium",
"58": "orange dahlia",
"59": "pink-yellow dahlia?",
"60": "cautleya spicata",
"61": "japanese anemone",
"62": "black-eyed susan",
"63": "silverbush",
"64": "californian poppy",
"65": "osteospermum",
"66": "spring crocus",
"67": "bearded iris",
"68": "windflower",
"69": "tree poppy",
"70": "gazania",
"71": "azalea",
"72": "water lily",
"73": "rose",
"74": "thorn apple",
"75": "morning glory",
"76": "passion flower",
"77": "lotus",
"78": "toad lily",
"79": "anthurium",
"80": "frangipani",
"81": "clematis",
"82": "hibiscus",
"83": "columbine",
"84": "desert-rose",
"85": "tree mallow",
"86": "magnolia",
"87": "cyclamen",
"88": "watercress",
"89": "canna lily",
"90": "hippeastrum",
"91": "bee balm",
"92": "ball moss",
"93": "foxglove",
"94": "bougainvillea",
"95": "camellia",
"96": "mallow",
"97": "mexican petunia",
"98": "bromelia",
"99": "blanket flower",
"100": "trumpet creeper",
"101": "blackberry lily"
}
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding class name.
for image, label in training_set.take(1):
first_image = image.numpy()
first_label = label.numpy()
flower_name = class_names[str(first_label)]
plt.imshow(first_image)
plt.title(f"Label: {flower_name}")
plt.axis('off')
plt.show()
Create Pipeline¶
# TODO: Create a pipeline for each set.
batch_size = 32
shuffle_buffer_size = 4
num_training_examples = info_set.splits['train'].num_examples
#Normalize the dataset as requested in the begining of the notebook
def normalize(image, label):
image = tf.image.resize(image, (224, 224)) # Resize to 224x224
image = tf.cast(image, tf.float32) / 255.0 # Normalize pixel values to [0, 1]
return image, label
training_batches = training_set.shuffle(num_training_examples//shuffle_buffer_size).map(normalize).batch(batch_size).prefetch(1)
validation_batches = validation_set.map(normalize).batch(batch_size).prefetch(1)
testing_batches = test_set.map(normalize).batch(batch_size).prefetch(1)
Build and Train the Classifier¶
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
- Load the MobileNet pre-trained network from TensorFlow Hub.
- Define a new, untrained feed-forward network as a classifier.
- Train the classifier.
- Plot the loss and accuracy values achieved during training for the training and validation set.
- Save your trained model as a Keras model.
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# TODO: Build and train your network.
mobilenet_url = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4" #I opted for MobileNet V3 Large (v3_large_075_224)
dense_layer_units = 512
dropout_rate = 0.2
num_classes = info_set.features['label'].num_classes
feature_extractor = hub.KerasLayer(mobilenet_url, input_shape=(224, 224, 3), trainable=False)
# This is a custom callback I created during troubleshooting to print/determin that early stopping is triggered.
class EarlyStoppingCallback(Callback):
def on_epoch_end(self, epoch, logs=None):
if self.model.stop_training:
print(f"\n----------- Training stopped at epoch {epoch + 1} due to early stopping. -----------")
# EarlyStopping callback much needed after my first afew runs without optimizing
early_stopping = EarlyStopping(
monitor='val_loss',
patience=3,
restore_best_weights=True
)
model = models.Sequential([
feature_extractor,
layers.Dense(dense_layer_units, activation='relu', kernel_regularizer=regularizers.l2(0.01)), # L2 Regularization for optimization
layers.Dropout(dropout_rate), # dropout for optimization
layers.Dense(num_classes, activation='softmax')
])
# I kept the default learning_rate of 0.001 for adam optimizer
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(
training_batches,
validation_data=validation_batches,
epochs=50,
callbacks=[early_stopping, EarlyStoppingCallback()]
)
Epoch 1/50 32/32 [==============================] - 13s 243ms/step - loss: 9.8119 - accuracy: 0.1422 - val_loss: 7.1401 - val_accuracy: 0.4588 Epoch 2/50 32/32 [==============================] - 8s 233ms/step - loss: 5.4587 - accuracy: 0.6020 - val_loss: 4.6141 - val_accuracy: 0.6314 Epoch 3/50 32/32 [==============================] - 8s 232ms/step - loss: 3.5264 - accuracy: 0.8147 - val_loss: 3.4816 - val_accuracy: 0.7245 Epoch 4/50 32/32 [==============================] - 8s 232ms/step - loss: 2.5896 - accuracy: 0.8961 - val_loss: 2.9206 - val_accuracy: 0.7343 Epoch 5/50 32/32 [==============================] - 8s 234ms/step - loss: 2.0356 - accuracy: 0.9422 - val_loss: 2.5019 - val_accuracy: 0.7529 Epoch 6/50 32/32 [==============================] - 8s 232ms/step - loss: 1.6818 - accuracy: 0.9529 - val_loss: 2.2313 - val_accuracy: 0.7618 Epoch 7/50 32/32 [==============================] - 8s 231ms/step - loss: 1.4027 - accuracy: 0.9735 - val_loss: 1.9981 - val_accuracy: 0.7618 Epoch 8/50 32/32 [==============================] - 8s 233ms/step - loss: 1.2445 - accuracy: 0.9647 - val_loss: 1.8615 - val_accuracy: 0.7647 Epoch 9/50 32/32 [==============================] - 8s 233ms/step - loss: 1.1229 - accuracy: 0.9706 - val_loss: 1.7511 - val_accuracy: 0.7716 Epoch 10/50 32/32 [==============================] - 8s 231ms/step - loss: 1.0021 - accuracy: 0.9843 - val_loss: 1.5994 - val_accuracy: 0.8049 Epoch 11/50 32/32 [==============================] - 8s 228ms/step - loss: 0.9155 - accuracy: 0.9745 - val_loss: 1.5171 - val_accuracy: 0.7941 Epoch 12/50 32/32 [==============================] - 8s 238ms/step - loss: 0.8229 - accuracy: 0.9882 - val_loss: 1.4593 - val_accuracy: 0.7931 Epoch 13/50 32/32 [==============================] - 8s 230ms/step - loss: 0.7711 - accuracy: 0.9853 - val_loss: 1.3965 - val_accuracy: 0.7873 Epoch 14/50 32/32 [==============================] - 8s 228ms/step - loss: 0.7702 - accuracy: 0.9745 - val_loss: 1.4699 - val_accuracy: 0.7637 Epoch 15/50 32/32 [==============================] - 8s 228ms/step - loss: 0.7492 - accuracy: 0.9765 - val_loss: 1.3829 - val_accuracy: 0.7912 Epoch 16/50 32/32 [==============================] - 8s 223ms/step - loss: 0.6910 - accuracy: 0.9824 - val_loss: 1.3651 - val_accuracy: 0.7755 Epoch 17/50 32/32 [==============================] - 8s 232ms/step - loss: 0.6703 - accuracy: 0.9824 - val_loss: 1.3576 - val_accuracy: 0.7843 Epoch 18/50 32/32 [==============================] - 8s 231ms/step - loss: 0.6590 - accuracy: 0.9882 - val_loss: 1.3358 - val_accuracy: 0.7892 Epoch 19/50 32/32 [==============================] - 8s 228ms/step - loss: 0.6355 - accuracy: 0.9853 - val_loss: 1.2947 - val_accuracy: 0.7833 Epoch 20/50 32/32 [==============================] - 8s 227ms/step - loss: 0.6234 - accuracy: 0.9843 - val_loss: 1.3187 - val_accuracy: 0.7843 Epoch 21/50 32/32 [==============================] - 8s 230ms/step - loss: 0.6464 - accuracy: 0.9735 - val_loss: 1.3010 - val_accuracy: 0.7990 Epoch 22/50 32/32 [==============================] - 8s 228ms/step - loss: 0.6088 - accuracy: 0.9863 - val_loss: 1.2565 - val_accuracy: 0.7931 Epoch 23/50 32/32 [==============================] - 8s 227ms/step - loss: 0.5886 - accuracy: 0.9853 - val_loss: 1.2461 - val_accuracy: 0.7990 Epoch 24/50 32/32 [==============================] - 8s 229ms/step - loss: 0.6040 - accuracy: 0.9775 - val_loss: 1.3251 - val_accuracy: 0.7676 Epoch 25/50 32/32 [==============================] - 8s 233ms/step - loss: 0.6090 - accuracy: 0.9794 - val_loss: 1.3176 - val_accuracy: 0.7559 Epoch 26/50 32/32 [==============================] - ETA: 0s - loss: 0.6169 - accuracy: 0.9755 ----------- Training stopped at epoch 26 due to early stopping. ----------- 32/32 [==============================] - 8s 237ms/step - loss: 0.6169 - accuracy: 0.9755 - val_loss: 1.2554 - val_accuracy: 0.7931
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
def plot_training_history(history):
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.figure(figsize=(12, 5))
# Accuracy plot
plt.subplot(1, 2, 1)
plt.plot(epochs, acc, label='Training Accuracy')
plt.plot(epochs, val_acc, label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.legend()
# Loss plot
plt.subplot(1, 2, 2)
plt.plot(epochs, loss, label='Training Loss')
plt.plot(epochs, val_loss, label='Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
plot_training_history(history)
Testing your Network¶
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# TODO: Print the loss and accuracy values achieved on the entire test set.
test_loss, test_accuracy = model.evaluate(testing_batches)
# Print the results
print(f"Test Loss: {test_loss}")
print(f"Test Accuracy: {test_accuracy}")
193/193 [==============================] - 24s 122ms/step - loss: 1.3720 - accuracy: 0.7622 Test Loss: 1.3720097541809082 Test Accuracy: 0.7622377872467041
Save the Model¶
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# TODO: Save your trained model as a Keras model.
model.save('my_model.keras')
Load the Keras Model¶
Load the Keras model you saved above.
# TODO: Load the Keras model
model = load_model('my_model.keras', custom_objects={'KerasLayer': hub.KerasLayer})
Inference for Classification¶
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
Image Pre-processing¶
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def process_image(image):
image_tensor = tf.convert_to_tensor(image, dtype=tf.float32)
image_resized = tf.image.resize(image_tensor, (224, 224))
image_normalized = image_resized / 255.0
return image_normalized.numpy()
To check your process_image function we have provided 4 images in the ./test_images/ folder:
- cautleya_spicata.jpg
- hard-leaved_pocket_orchid.jpg
- orange_dahlia.jpg
- wild_pansy.jpg
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
from PIL import Image
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)
processed_test_image = process_image(test_image)
fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Inference¶
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
# TODO: Create the predict function
def predict(image_path, model, top_k=5):
# Load and preprocess the image
image = Image.open(image_path)
image_np = np.asarray(image)
processed_image = process_image(image_np)
# Expand dimensions to add batch size (1, 224, 224, 3) as requested above
input_tensor = np.expand_dims(processed_image, axis=0)
# Perform prediction
predictions = model.predict(input_tensor)
# Get top K predictions
top_k_indices = np.argsort(predictions[0])[-top_k:][::-1]
top_k_probs = predictions[0][top_k_indices]
top_k_classes = [str(index) for index in top_k_indices] # Just Converting indices to string similar to class_names[str(first_label)]
return top_k_probs, top_k_classes
# Testing one image quickly ..
image_path = "./test_images/orange_dahlia.jpg"
probs, classes = predict(image_path, model, top_k=5)
print("Probabilities:", probs)
print("Classes:", classes)
1/1 [==============================] - 1s 528ms/step Probabilities: [0.7543986 0.08066276 0.03979915 0.03646277 0.02256478] Classes: ['4', '58', '65', '40', '70']
Sanity Check¶
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
- cautleya_spicata.jpg
- hard-leaved_pocket_orchid.jpg
- orange_dahlia.jpg
- wild_pansy.jpg
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:
You can convert from the class integer labels to actual flower names using class_names.
# TODO: Plot the input image along with the top 5 classes
def plot_image_with_probs(image_path, model, class_names, top_k=5):
probs, classes = predict(image_path, model, top_k)
class_labels = [class_names[str(cls)] for cls in classes]
image = Image.open(image_path)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.imshow(image)
ax1.axis("off")
ax1.set_title("Input Image")
filename = image_path.split("/")[-1] # For better display/UI I'd like to Extract the file name from the path ..
ax1.text(0.5, 0.05, f"File: {filename}", ha="center", va="center", transform=ax1.transAxes, fontsize=12, color="white", bbox=dict(facecolor="black", alpha=0.6))
# Right: Plot probabilities as a bar chart
y_pos = np.arange(len(class_labels))
ax2.barh(y_pos, probs, color="blue", alpha=0.6)
ax2.set_yticks(y_pos)
ax2.set_yticklabels(class_labels)
ax2.invert_yaxis() # Highest probability at the top
ax2.set_xlabel("Probability")
ax2.set_title("Class Probability")
plt.tight_layout()
plt.show()
test_images = [
"./test_images/cautleya_spicata.jpg",
"./test_images/hard-leaved_pocket_orchid.jpg",
"./test_images/orange_dahlia.jpg",
"./test_images/wild_pansy.jpg"
]
for image_path in test_images:
print(f"Processing: {image_path}")
plot_image_with_probs(image_path, model, class_names)
Processing: ./test_images/cautleya_spicata.jpg 1/1 [==============================] - 0s 31ms/step
Processing: ./test_images/hard-leaved_pocket_orchid.jpg 1/1 [==============================] - 0s 45ms/step
Processing: ./test_images/orange_dahlia.jpg 1/1 [==============================] - 0s 29ms/step
Processing: ./test_images/wild_pansy.jpg 1/1 [==============================] - 0s 42ms/step